const http = require("http");

// 请求测试
(function () {
  return;
  const url = require("url");
  const server = http.createServer((req, res) => {
    console.log(req.url);
    console.log(url.parse(req.url));
    console.log("请求头", req.headers);
    console.log("请求方法", req.method);
    let requ = "";
    req.on("data", (chunk) => {
      console.log(chunk);
      requ += chunk.toString("utf-8");
    });
    req.on("close", (chunk) => {
      console.log("关闭了", requ);
    });

    res.setHeader("a", "1");
    res.write("你好!");
    res.end();
  });
  server.listen("1111");
  server.on("listening", () => {
    console.log("监听1111端口了");
  });
})();

// 静态资源服务器
(function () {
  // return
  const fs = require("fs");
  const URL = require("url");
  const path = require("path");
  async function getStat(filename) {
    try {
      return await fs.promises.stat(filename);
    } catch (error) {
      return null;
    }
  }
  /**
   * 得到要处理的文件信息
   */
  async function getFileInfo(url) {
    const urlObj = URL.parse(url);
    let filename; // 要处理的文件路径
    filename = path.resolve(__dirname, "public", urlObj.pathname.substr(1));
    let stat = await getStat(filename);
    if (!stat) {
      // 文件不存在
      // 假设文件后面加一个index.html
      console.log("文件不存在");
    } else if (stat.isDirectory()) {
      // 文件是一个目录
      filename = path.resolve(filename, "index.html");
      stat = await getStat(filename);
      if (!stat) {
        // 文件还是不存在
        console.log("文件不存在");
      } else {
        console.log("正常的文件", filename);
        return await fs.promises.readFile(filename);
      }
    } else {
      console.log("正常的文件");
      return await fs.promises.readFile(filename);
    }
    console.log(filename, stat);
  }
  async function handler(req, res) {
    const info = await getFileInfo(req.url);
    if (info) {
      res.write(info);
    } else {
      res.statusCode = 404;
      res.write("Resource is not exist");
    }
    // res.write("hello!!!");
    res.end();
  }
  const server = http.createServer(handler);
  server.listen(1234);
  server.on("listening", (req, res) => {
    console.log("监听端口1234");
  });
})();
